<template>
	<view class="upload-gallery">
		<view class="upload-list">
			<view class="upload-list__item" v-for="(item,index) in value" :key="item">
				<view class="upload-list__delete" @tap="handleDelete(index)">×</view>
				<image class="upload-list__image" mode="aspectFill" :src="host + item" @tap="handlePreview(index)"></image>
			</view>
			<view class="upload-list__item" v-if="value.length < count">
				<view class="upload-list__upload iconfontPT" @tap="handleUpload">
					<view class="iconfontPT icontupian02 upload-list__icon"></view>
					<view>添加图片</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import Upload from '@/utils/upload.js'
	export default {
		props:{
			count:{
				type:Number, 
				default: 3 // 限制上传数量
			},
			value:{
				type:Array,
				default:()=>[] 
			},
			cdn:{
				type:Boolean,
				default:false // 是否使用七牛 CDN
			},
			checkType:{
				type:String,
				default: null // 鉴黄模块 md、zj
			}
		},
		// BUG: https://github.com/dcloudio/uni-app/issues/1274
		model:{
			prop: 'value',
			event: 'input'
		},
		computed:{
			host(){
				return this.cdn ? this.$baseHost.qiniuHost : this.$baseHost.car
			},
			url(){
				return `${this.$baseHost.car}/api/common/${this.cdn ? 'upImage' : 'upload'}`
			},
			upload(){
				return new Upload({url:this.url, checkType:this.checkType })
			}
		},
		methods:{
			async handleUpload(){
				try{
					const { data } = await this.upload.uploadImage()
					const list = [...this.value,...data.map(item => item.url)]
					this.$emit('input',list)
					this.$emit('change',list)
				}catch(e){
					console.warn(e.message)
				}
			},
			handleDelete(index){
				const list = this.value.filter((item,i)=> index !== i)
				this.$emit('input',list)
				this.$emit('change',list)
			},
			handlePreview(current){
				uni.previewImage({urls:this.value.map(item=> this.host + item),current})
			}
		},
	}
</script>

<style lang="scss">
	.upload-list{
		display: flex;
		flex-wrap: wrap;
		margin: 0 -10rpx;
		&__item{
			width: calc((100vw - 40rpx) / 3);
			height: calc((100vw - 40rpx) / 3);
			padding: 10rpx;
			position: relative;
			box-sizing: border-box;
		}
		&__image{
			background-color: #CCCCCC;
			width: 100%;
			height: 100%;
		}
		&__delete{
			position: absolute;
			top: 0;
			right: 5rpx;
			font-size: 40rpx;
			line-height: 1em;
			width: 50rpx;
			height: 50rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			color: #FFFFFF;
			text-shadow: 1rpx 1rpx #CCCCCC;
		}
		&__upload{
			width: 100%;
			height: 100%;
			background-color:#f8f8f8;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			font-size: 24rpx;
		}
		&__icon{
			margin-bottom: 10rpx;
		}
	}
</style>
